<template>
  <!-- <iframe src="/public/luckyexcel-import/index.html" frameborder="0"></iframe> -->
  <div class="dynamicReport">
    <el-row>
      <el-col :span="6" style="padding: 0 20px"
        ><div class="quotaDim" style="height: 100%">
          <div
            class="quotatree"
            style="border: 1px solid #dfe4ed; height: 305px; margin: 20px 0 5px"
          >
            <div
              class="commomDim"
              style="
                height: 32px;
                line-height: 32px;
                text-align: center;
                font-size: 14px;
              "
            >
              指标
            </div>
            <QuotaTree
              @computedQuota="getQuotaNode"
              @dragNode="handleDragNode"
              class="quoTree"
              :showcheckbox="false"
            />
          </div>
          <div
            style="
              height: 305px;
              text-align: center;
              overflow: auto;
              font-size: 14px;
              border: 1px solid #d8dce5;
            "
          >
            <div
              class="commomDim"
              style="
                height: 32px;
                line-height: 32px;
                text-align: center;
                border: 1px solid #d8dce5;
              "
            >
              维度
            </div>
            <div class="common">
              <el-tree
                draggable
                @check-change="checkChange"
                node-key="id"
                ref="dimTree"
                show-checkbox
                :data="commonDimensionList"
                :props="dimTreeProps"
              ></el-tree>
            </div>
          </div>
        </div>
        <div style="margin: 10px 0">
          <el-select
            style="margin-right: 10px; width: 100%"
            v-model="quota.typeId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in computedType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <!-- <el-button @click="creatQuotaVal" type="primary">关联维度</el-button> -->
      </el-col>
      <el-col :span="18"
        ><div>
          <div style="margin: 20px 0">
            <el-button type="primary" @click="importReport" plain
              >导入Excel文件</el-button
            >
            <!-- <el-button type="primary" @click="refreshData" plain
              >生成报表</el-button
            > -->
            <el-button type="primary" @click="exportHtml" plain
              >导出成HTML文件</el-button
            >
            <el-button type="primary" @click="exportExcel" plain
              >导出成Excel文件</el-button
            >
          </div>
          <div v-loading="loading" element-loading-text="正在获取数据">
            <iframe
              id="report-iframe"
              frameborder="0"
              scrolling="yes"
              style="background-color:transparent; position：absolute;width: 100%;
            height:650px; top: 0;right:0;left:0;bottom:0;"
              src="/lucky/report.html"
            ></iframe>
          </div></div
      ></el-col>
    </el-row>
  </div>
</template>
<script>
import QuotaTree from "@/views/quota/modeling/QuotaTree.vue";
import { quotaFormula } from "@/api/quota/reportUpload/reportUpload.js";
import {
  getBeMixedTree,
  queryComputeType,
  getQuotaReportValue,
} from "@/api/quota/define/define.js";
export default {
  components: {
    QuotaTree,
  },
  data() {
    return {
      loading: false,
      dimTreeProps: {
        children: "children",
        label: "dimensionName",
      },
      //当前拖拽指标
      quota: {
        typeId: "0",
        id: undefined,
        dimensionIds: [],
        col: undefined,
        order: undefined,
        row: undefined,
        value: undefined,
      },
      //含有指标值的指标列表
      quotaList: [],
      cellData: [],
      //拖拽指标节点
      quotas: [],
      //计算类型
      computedType: [],
      //指标值类型
      typeId: "0",
      //共有维度
      commonDimensionList: [],
      showAll: true,
      dimensionIds:[]
    };
  },
  computed: {
    getId: function () {
      return this.quota.id;
    },
  },
  created() {
    //获取计算类型
    queryComputeType().then((res) => {
      this.computedType = res.data;
    });
  },
  watch: {
    getId: {
      handler(newVal, oldVal) {
        let quotaIds = [];
        quotaIds.push(newVal);
        getBeMixedTree(quotaIds).then((res) => {
          this.commonDimensionList = this.handleTree(res.data, "id", "upperId");
          this.$nextTick(() => {
            if (this.showAll) {
              this.$refs.dimTree.setCheckedNodes(this.commonDimensionList);
            }
          });
        });
      },
    },
  },
  methods: {
    checkChange(){
      this.dimensionIds = this.$refs.dimTree.getCheckedKeys(true)
    },
    //导出带格式的excel文件
    exportExcel() {
      document.getElementById("report-iframe").contentWindow.expFile();
    },
    //点击指标节点
    getQuotaNode(data) {
      
      this.quota.id = data.id;
      let idx = this.quotaList.findIndex((item) => {
        return item.id == data.id;
      });
      
      if (idx === -1) {
        // this.showAll = true;
        // this.$refs.dimTree.setCheckedKeys(this.dimensionIds);
      } else {
        // this.showAll = false;
        this.$nextTick(() => {  
          // this.$refs.dimTree.setCheckedKeys(this.quotaList[idx].dimensionIds);
        });
      }
    },
    //点击关联维度按钮
    // creatQuotaVal() {
    //   this.quota.dimensionIds = this.$refs.dimTree.getCheckedKeys(true);
    //   if (this.quota.dimensionIds.length === 0) {
    //     this.$message({
    //       message: '请先为指标选择需要关联维度及计算方式',
    //       type: 'warning'
    //     });
    //     return;
    //   }
    //   this.quotaList.unshift(this.quota);
    //   let id = this.quota.id
    //   this.quota = {
    //     typeId: "0",
    //     id: id,
    //     dimensionIds: [],
    //     order: undefined,
    //     col: undefined,
    //     row: undefined,
    //     value: undefined,
    //   };
    // },

    //单击指标节点
    //  getQuotaNode(node){
    //    this.quota.id = node.id
    //  },
    //导出报表
    exportHtml() {
      document.getElementById("report-iframe").contentWindow.exportHtml();
      //将quotaList及luckysheet配置项传给后台
      this.quotaList = [];
    },
    //导入报表
    importReport() {
      document.getElementById("report-iframe").contentWindow.importExcel();
    },
    //更新luckysheet
    refreshData() {
      if (this.quotas.length === 0) {
        return;
      }
      this.quotas.forEach((item) => {
        document
          .getElementById("report-iframe")
          .contentWindow.luckysheet.setCellValue(...item);
      });
      this.quotas = [];
      this.quotaList = [];
    },
    //获取指标节点
    handleDragNode(data) {
      this.getQuotaNode(data);
      this.quota.dimensionIds = this.$refs.dimTree.getCheckedKeys(true);
      console.log(this.quota.dimensionIds);
     
      if (this.quota.dimensionIds.length === 0) {
        this.$message({
          message: "请先为指标选择需要关联维度及计算方式",
          type: "warning",
        });
        return;
      }
      //调用接口获取指标值
      let param = {};
      param.quotaId = this.quota.id;
      param.dimIdList = this.quota.dimensionIds;
      param.type = this.quota.typeId;
      this.loading = true;
      console.log(1, this.quota);
      getQuotaReportValue(param)
        .then((res) => {
          console.log(2, this.quota);
          this.loading = false;
          this.quota.value = res.data;
          let rc = document
            .getElementById("report-iframe")
            .contentWindow.luckysheet.getRange();
          this.cellData = document
            .getElementById("report-iframe")
            .contentWindow.luckysheet.getLuckysheetfile();
          let sheetIdx = 0;
          this.cellData.forEach((item) => {
            if (item.status == 1) {
              sheetIdx = item.order;
            }
          });

          // this.quotas.push([
          //   rc[0].row[0],
          //   rc[0].column[0],
          //   data.id,
          //   { order: sheetIdx },
          // ]);
          this.quota.col = rc[0].column[0];
          this.quota.row = rc[0].row[0];
          this.quota.order = sheetIdx;
          console.log(this.quota);
          
          this.quotaList.unshift(this.quota);

          document
            .getElementById("report-iframe")
            .contentWindow.luckysheet.setCellValue(
              rc[0].row[0],
              rc[0].column[0],
              this.quota.value
            );
          let id = this.quota.id;
          this.quota = {
            typeId: "0",
            id: id,
            dimensionIds: [],
            order: undefined,
            col: undefined,
            row: undefined,
            value: undefined,
          };
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("拖拽指标之失败");
          this.loading = false;
        });

      // this.quotaList.push(data);
      // this.currentQuota = data;

      // this.cellData = document
      //   .getElementById("report-iframe")
      //   .contentWindow.luckysheet.getLuckysheetfile();
    },

    //传url值
    setUrlToIframe() {
      let arr = JSON.parse(this.$route.params.data);
      document.getElementById("report-iframe").onload = () => {
        document
          .getElementById("report-iframe")
          .contentWindow.importJsonData(JSON.parse(arr));
      };
    },
    //获取维度关联报表数据
    getQuotaFormula() {
      quotaFormula()
        .then((res) => {
          this.reportData = JSON.parse(res.data);
        })
        .catch((error) => {
          this.$message("获取数据失败");
        });
    },
  },
  mounted() {
    // this.getQuotaFormula()
    this.setUrlToIframe();
  },
};
</script>
<style lang="less">
.dynamicReport {
  .el-tree {
    display: inline-block;
  }
  .common {
    overflow: auto;
    text-align: left;

    .el-tree__empty-text {
      display: none;
    }
  }
  .quotatree {
    overflow: auto;
  }

  .quoTree {
    text-align: left;
  }
}
</style>
